package com.yuanjiu.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.yuanjiu.pojo.yuanjiu.CategoryIdName;
import com.yuanjiu.pojo.yuanjiu.CommentObject;
import com.yuanjiu.pojo.yuanjiu.JiuObject;
import com.yuanjiu.service.yuanjiu.CategoryService;
import com.yuanjiu.service.yuanjiu.HomeService;
import com.yuanjiu.service.yuanjiu.ProductService;
import com.yuanjiu.vo.yuanjiu.ProductVo;

@Controller
public class ProductController {

	@Autowired
	private ProductService productService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private HomeService homeService;
	
	@RequestMapping("single_product")
	public String single(HttpServletRequest request,JiuObject jiuObject, Model model){
		
		//获取详情
		JiuObject jiuObject2 = productService.getProductById(jiuObject);
		model.addAttribute("jiuObject", jiuObject2);
		
		//分类信息
		if(jiuObject2 != null && StringUtils.isNotEmpty(jiuObject2.getCategory())){
			ProductVo productVo = new ProductVo();
			productVo.setCid(jiuObject2.getCategory());
			ProductVo productVo2 = categoryService.getProductVoByCid(productVo);
			model.addAttribute("productVo", productVo2);
		}
		
		//获取图片列表
		List<String> imgList = new ArrayList<String>(); 
		if(jiuObject2 != null && StringUtils.isNotEmpty(jiuObject2.getPic())){
			String imgs = jiuObject2.getPic();
				//1919图片Url特殊处理
				if(jiuObject2.getWebCode() != null && jiuObject2.getWebCode().equals("2")){
					String[] imgAll = jiuObject2.getPic().split("\\?|,");
					for(String tmp : imgAll){
						if(StringUtils.isNotEmpty(tmp) && tmp.startsWith("http")){
							imgList.add(tmp);
						}
					}

				}else{
					String[] imgAll = imgs.split(",");
					for(String tmp: imgAll){
						if(StringUtils.isNotEmpty(tmp) && tmp.startsWith("http:")){
							imgList.add(tmp);
						}
						
					}
				}
			model.addAttribute("imgList", imgList);
		}
		//获取评论
		List<CommentObject> commentList = productService.getCommentByGoodsId(jiuObject);
		model.addAttribute("commentList", commentList);
		
		
		//获取所有的一级分类
		List<CategoryIdName> categories = homeService.findAllCategories(); 
		model.addAttribute("categoryList", categories);
		
		return "single_products";
	}
}
